<template>
  <div class="seckill-page min-h-screen bg-gradient-to-br from-red-50 via-orange-50 to-red-100">
    <!-- Hero Section -->
    <div class="relative overflow-hidden bg-gradient-to-r from-red-600 via-orange-600 to-red-700">
      <div class="absolute inset-0">
        <div class="absolute inset-0 bg-black opacity-20"></div>
        <div class="absolute top-0 left-0 w-full h-full">
          <div class="absolute top-10 left-10 w-32 h-32 bg-white bg-opacity-10 rounded-full animate-pulse"></div>
          <div class="absolute top-20 right-20 w-24 h-24 bg-white bg-opacity-10 rounded-full animate-pulse delay-1000"></div>
          <div class="absolute bottom-10 left-1/3 w-40 h-40 bg-white bg-opacity-10 rounded-full animate-pulse delay-2000"></div>
        </div>
      </div>
      
      <div class="relative container mx-auto px-4 py-16">
        <div class="text-center text-white">
          <h1 class="text-5xl font-bold mb-4 animate-fade-in">
            <span class="bg-gradient-to-r from-yellow-300 to-red-300 bg-clip-text text-transparent">
              限时秒杀
            </span>
          </h1>
          <p class="text-xl mb-8 opacity-90 animate-fade-in-delay">抢购倒计时，手慢无！</p>
          <div class="flex justify-center space-x-8 text-sm">
            <div class="flex items-center">
              <div class="w-3 h-3 bg-yellow-400 rounded-full mr-2 animate-ping"></div>
              <span>限时抢购</span>
            </div>
            <div class="flex items-center">
              <div class="w-3 h-3 bg-red-400 rounded-full mr-2 animate-ping delay-500"></div>
              <span>库存有限</span>
            </div>
            <div class="flex items-center">
              <div class="w-3 h-3 bg-orange-400 rounded-full mr-2 animate-ping delay-1000"></div>
              <span>超低价格</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="container mx-auto px-4 py-8">
      <div class="bg-white rounded-2xl shadow-lg p-6">
        <el-skeleton :rows="5" animated />
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="container mx-auto px-4 py-8">
      <div class="bg-white rounded-2xl shadow-lg p-6 text-center">
        <el-icon size="48" class="text-gray-400 mb-4"><Warning /></el-icon>
        <p class="text-gray-600 mb-4">{{ error }}</p>
        <el-button type="primary" @click="fetchPromotions">重新加载</el-button>
      </div>
    </div>

    <!-- Content -->
    <div v-else class="container mx-auto px-4 py-8">
      <!-- Seckill Products -->
      <div class="bg-white rounded-2xl shadow-lg p-6">
        <h3 class="text-xl font-bold text-gray-800 mb-6">正在秒杀</h3>
        
        <div v-if="promotions.length === 0" class="text-center py-12">
          <el-icon size="64" class="text-gray-300 mb-4"><ShoppingBag /></el-icon>
          <p class="text-gray-500 text-lg">暂无秒杀活动</p>
          <p class="text-gray-400 text-sm mt-2">敬请期待更多秒杀活动</p>
        </div>

        <!-- Show promotions even if details are empty -->
        <div v-else-if="seckillProducts.length === 0 && promotions.length > 0" class="space-y-6">
          <div
            v-for="promotion in promotions"
            :key="promotion.billNo"
            class="bg-gradient-to-br from-red-50 to-orange-50 rounded-xl p-6 border border-red-200"
          >
            <div class="text-center">
              <h4 class="text-xl font-bold text-gray-800 mb-2">{{ promotion.promName }}</h4>
              <p class="text-sm text-gray-600 mb-4">{{ promotion.billCode }}</p>
              <div class="bg-red-500 text-white px-4 py-2 rounded-full text-sm font-bold inline-block mb-4">
                {{ getPromotionStatus(promotion) }}
              </div>
              <div class="text-sm text-gray-600">
                活动时间: {{ formatDate(promotion.startTime) }} - {{ formatDate(promotion.endTime) }}
              </div>
              <div class="mt-4 text-orange-600 font-medium">
                商品详情即将更新，敬请期待！
              </div>
            </div>
          </div>
        </div>

        <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          <div
            v-for="product in seckillProducts"
            :key="product.id"
            class="bg-gradient-to-br from-red-50 to-orange-50 rounded-xl overflow-hidden border border-red-200 hover:shadow-lg transition-all duration-300 hover:-translate-y-1 cursor-pointer"
          >
            <!-- Product Image -->
            <div class="relative">
              <img
                :src="product.goodsInfo.mainPic || '/images/no.jpg'"
                :alt="product.goodsInfo.title"
                class="w-full h-48 object-cover"
                @error="handleImageError"
              />
              <div class="absolute top-2 left-2 bg-red-500 text-white px-2 py-1 rounded-full text-xs font-bold">
                秒杀中
              </div>
              <div class="absolute top-2 right-2 bg-black bg-opacity-50 text-white px-2 py-1 rounded-full text-xs">
                {{ calculateDiscount(product) }}折
              </div>
            </div>

            <!-- Product Info -->
            <div class="p-4">
              <!-- 商品名称和处方药标签 -->
              <div class="flex items-start gap-2 mb-2">
                <h4 class="font-bold text-gray-800 mb-2 line-clamp-2 flex-1">{{ product.goodsInfo.title }}</h4>
              </div>

              <!-- 生产厂家 -->
              <div class="text-sm text-gray-600 mb-2">{{ product.goodsInfo.manufacturer }}</div>

              <!-- 规格信息 -->
              <div class="flex items-center gap-2 mb-2">
                <el-tag size="small" class="border !bg-blue-50 !border-blue-100 !text-gray-700">{{ product.goodsInfo.goodsSpec }}</el-tag>
                <el-tag size="small" class="border !bg-blue-50 !border-blue-100 !text-gray-700">{{ product.goodsInfo.unit }}</el-tag>
              </div>

              <!-- 分类信息 -->
              <div class="flex items-center gap-2 mb-2">
                <el-tag size="small" class="border !bg-gray-50 !border-gray-200 !text-gray-600">{{ product.goodsInfo.qCategory }}</el-tag>
              </div>

              <!-- 中包装信息 -->
              <div class="packaging-info mb-2 space-y-1">
                <!-- 包装类型行 -->
                <div class="flex items-center gap-2">
                  <el-tag 
                    size="small" 
                    :type="product.goodsInfo.midpack > 1 ? 'success' : 'info'" 
                    :class="product.goodsInfo.midpack > 1 ? '!bg-green-50' : '!bg-blue-50'"
                  >
                    {{ product.goodsInfo.midpack > 1 ? '中包装' : '件包装' }}
                  </el-tag>
                  <span class="text-sm text-gray-600">
                    {{ product.goodsInfo.midpack > 1 ? `${product.goodsInfo.midpack}${product.goodsInfo.unit}` : '件包装销售' }}
                  </span>
                </div>
                
                <!-- 拆零支持行 -->
                <div v-if="product.goodsInfo.midpack > 1" class="flex items-center">
                  <el-tag 
                    size="small" 
                    :type="product.goodsInfo.isMidpackSaleDisabled === 0 ? 'success' : 'warning'"
                    effect="plain"
                    class="!text-xs"
                  >
                    {{ product.goodsInfo.isMidpackSaleDisabled === 0 ? '支持拆零' : '不支持拆零' }}
                  </el-tag>
                  <span v-if="product.goodsInfo.isMidpackSaleDisabled === 1" class="text-xs text-orange-600 ml-2">
                    需按{{ product.goodsInfo.midpack }}{{ product.goodsInfo.unit }}倍数购买
                  </span>
                </div>
              </div>

              <!-- 近效期信息 -->
              <div v-if="product.goodsInfo.nearestExpiredDate" class="batch-info mb-2">
                <div class="flex items-center gap-2">
                  <span class="text-xs text-gray-500">有效期:</span>
                  <span class="text-xs text-orange-600 font-medium">{{ formatDate(product.goodsInfo.nearestExpiredDate) }}</span>
                </div>
              </div>

              <!-- 活动时间 -->
              <div v-if="product.promotion" class="batch-info mb-2">
                <div class="flex items-center gap-2">
                  <span class="text-xs text-gray-500">活动时间:</span>
                  <span class="text-xs text-blue-600 font-medium">{{ formatDate(product.promotion.startTime) }} - {{ formatDate(product.promotion.endTime) }}</span>
                </div>
              </div>
              
              <!-- Price -->
              <div class="flex items-center justify-between mb-3">
                <div>
                  <span class="text-2xl font-bold text-red-600">¥{{ Number(product.seckillPrice).toFixed(2) }}</span>
                  <span class="text-sm text-gray-500 line-through ml-2">¥{{ Number(product.goodsInfo.price).toFixed(2) }}</span>
                </div>
                <div class="text-sm text-green-600 font-medium">
                  省¥{{ (Number(product.goodsInfo.price) - Number(product.seckillPrice)).toFixed(2) }}
                </div>
              </div>

              <!-- Stock Progress -->
              <div class="mb-4">
                <div class="flex justify-between text-sm text-gray-600 mb-1">
                  <span>库存</span>
                  <span>剩余{{ Math.floor(Number(product.seckillStorNum)) }}件</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div
                    class="bg-gradient-to-r from-red-500 to-orange-500 h-2 rounded-full transition-all duration-300"
                    :style="{ width: `${Math.max(10, (Math.floor(Number(product.seckillStorNum)) / (Math.floor(Number(product.seckillStorNum)) + Math.floor(Number(product.seckillNum)))) * 100)}%` }"
                  ></div>
                </div>
              </div>

              <!-- Action Button -->
              <div class="space-y-2">
                <div class="flex items-center space-x-2">
                  <label class="text-sm text-gray-600">抢购数量:</label>
                  <el-input-number
                    v-model="product.purchaseQuantity"
                    :min="1"
                    :max="Math.min(Math.floor(Number(product.seckillStorNum)), Math.floor(Number(product.seckillNum)))"
                    size="small"
                    class="flex-1"
                  />
                </div>
                                  <div class="text-xs text-gray-500 mb-1">
                    单次最多可抢购{{ Math.floor(Number(product.seckillNum)) }}件，剩余库存{{ Math.floor(Number(product.seckillStorNum)) }}件
                  </div>
                <button
                  @click.stop="createSeckillOrder(product)"
                  :disabled="Math.floor(Number(product.seckillStorNum)) <= 0 || isCreatingSeckillOrder"
                  class="w-full py-2 rounded-lg font-medium transition-all duration-200"
                  :class="Math.floor(Number(product.seckillStorNum)) > 0 && !isCreatingSeckillOrder
                    ? 'bg-gradient-to-r from-red-500 to-orange-500 hover:from-red-600 hover:to-orange-600 text-white' 
                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'"
                >
                  {{ Math.floor(Number(product.seckillStorNum)) > 0 
                    ? (isCreatingSeckillOrder ? '抢购中...' : '立即抢购') 
                    : '已抢完' }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- How it works -->
      <div class="bg-white rounded-2xl shadow-lg p-6 mt-8">
        <h3 class="text-xl font-bold text-gray-800 mb-6">秒杀规则说明</h3>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
          <div class="text-center">
            <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <el-icon size="24" class="text-red-600"><Timer /></el-icon>
            </div>
            <h4 class="font-semibold text-gray-800 mb-2">限时抢购</h4>
            <p class="text-sm text-gray-600">秒杀商品限时限量，售完即止</p>
          </div>
          <div class="text-center">
            <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <el-icon size="24" class="text-red-600"><PriceTag /></el-icon>
            </div>
            <h4 class="font-semibold text-gray-800 mb-2">超低价格</h4>
            <p class="text-sm text-gray-600">秒杀价格远低于市场价，机不可失</p>
          </div>
          <div class="text-center">
            <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <el-icon size="24" class="text-red-600"><ShoppingBag /></el-icon>
            </div>
            <h4 class="font-semibold text-gray-800 mb-2">限购数量</h4>
            <p class="text-sm text-gray-600">每次秒杀有最大限购数量，请合理选择</p>
          </div>
          <div class="text-center">
            <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <el-icon size="24" class="text-red-600"><Lightning /></el-icon>
            </div>
            <h4 class="font-semibold text-gray-800 mb-2">直接下单</h4>
            <p class="text-sm text-gray-600">库存有限，直接生成订单，抢购更快捷</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Warning, ShoppingBag, Timer, PriceTag, Lightning } from '@element-plus/icons-vue'
import { promotionApi } from '@/api'
import type { SeckillPromotion, SeckillDetail } from '@/api/modules/promotion'

// Extended SeckillDetail with purchase quantity and promotion info
interface ExtendedSeckillDetail extends SeckillDetail {
  purchaseQuantity?: number
  promotion?: SeckillPromotion
}

const router = useRouter()
const loading = ref(true)
const error = ref('')
const promotions = ref<SeckillPromotion[]>([])
const seckillProducts = ref<ExtendedSeckillDetail[]>([])

// Methods
async function fetchPromotions() {
  try {
    loading.value = true
    error.value = ''
    
    const response = await promotionApi.getPromotionsByType('MS')
    
    // response is ApiResponse<Promotion[]> due to response interceptor
    if (response.code === 1000 && response.data) {
      // Filter by Chinese promType or English promType and only active promotions
      const allPromotions = (response.data || []).filter((p: any) => 
        p.promType === 'MS' || p.promType === '秒杀'
      ) as SeckillPromotion[]
      
      // Only show non-ended promotions (including not started and active)
      promotions.value = allPromotions.filter(promotion => !isPromotionEnded(promotion))
      
      // Extract all seckill products from active promotions
      seckillProducts.value = []
      promotions.value.forEach(promotion => {
        if (promotion.details && promotion.details.length > 0) {
          seckillProducts.value.push(...promotion.details.map(detail => ({
            ...detail,
            purchaseQuantity: 1, // Initialize with 1
            promotion: promotion // Add promotion info
          })))
        }
      })
    } else {
      throw new Error(response.message || '获取秒杀活动失败')
    }
  } catch (err: any) {
    error.value = err.message || '网络错误，请稍后重试'
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}


function isPromotionEnded(promotion: SeckillPromotion): boolean {
  const now = new Date()
  const endTime = new Date(promotion.endTime)
  
  return promotion.status === 0 || now > endTime
}

function calculateDiscount(product: SeckillDetail): string {
  const discount = (product.seckillPrice / product.goodsInfo.price * 10).toFixed(1)
  return discount
}

function getPromotionStatus(promotion: SeckillPromotion): string {
  const now = new Date()
  const startTime = new Date(promotion.startTime)
  const endTime = new Date(promotion.endTime)
  
  if (promotion.status === 0) return '已停用'
  if (now < startTime) return '未开始'
  if (now > endTime) return '已结束'
  return '进行中'
}

function formatDate(dateString: string): string {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 秒杀订单创建状态
const isCreatingSeckillOrder = ref(false)

async function createSeckillOrder(product: ExtendedSeckillDetail) {
  if (Math.floor(Number(product.seckillStorNum)) <= 0) {
    ElMessage.warning('商品已抢完')
    return
  }
  
  if (isCreatingSeckillOrder.value) {
    return
  }
  
  isCreatingSeckillOrder.value = true
  
  const quantity = product.purchaseQuantity || 1
  
  try {
    // 确认对话框
    await ElMessageBox.confirm(
      `确认抢购 ${product.goodsInfo.title} ${quantity}件吗？\n单价：¥${Number(product.seckillPrice).toFixed(2)}\n总价：¥${(Number(product.seckillPrice) * quantity).toFixed(2)}\n\n限购说明：单次最多可抢购${Math.floor(Number(product.seckillNum))}件`,
      '确认抢购',
      {
        confirmButtonText: '确认抢购',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // Find the promotion that contains this product
    const promotion = promotions.value.find(p => 
      p.details.some(d => d.goodsId === product.goodsId)
    )
    
    if (!promotion) {
      ElMessage.error('找不到对应的促销活动')
      return
    }
    
    const response = await promotionApi.createSeckillOrder({
      billNo: promotion.billNo,
      goodsId: product.goodsId,
      quantity: quantity,
      remark: '秒杀订单'
    })
    
    if (response.code === 1000) {
      ElMessage.success(`秒杀成功！订单号：${response.data.orderNum}`)
      // Update stock (simulate)
      product.seckillStorNum = Math.max(0, Math.floor(Number(product.seckillStorNum)) - quantity)
      // Navigate to my orders page
      router.push('/my-orders')
    } else {
      throw new Error(response.message || '秒杀失败')
    }
  } catch (error: any) {
    if (error === 'cancel') {
      // 用户取消，不显示错误信息
      return
    }
    ElMessage.error(error.message || '秒杀失败，请重试')
  } finally {
    isCreatingSeckillOrder.value = false
  }
}

// Handle image error
function handleImageError(event: Event) {
  const img = event.target as HTMLImageElement
  if (img) {
    img.src = '/images/no.jpg'
  }
}

// Lifecycle
onMounted(() => {
  fetchPromotions()
})
</script>

<style scoped>
@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fade-in-delay {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in {
  animation: fade-in 1s ease-out;
}

.animate-fade-in-delay {
  animation: fade-in-delay 1s ease-out 0.3s both;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 包装信息样式 */
.packaging-info {
  background: #fafafa;
  border-radius: 4px;
  padding: 6px 8px;
  border: 1px solid #f0f0f0;
}

.packaging-info .el-tag {
  border-radius: 2px;
  font-weight: 500;
}

.packaging-info .el-tag--small {
  height: 18px;
  line-height: 16px;
  padding: 0 4px;
  font-size: 11px;
}

/* 原有样式 */
.seckill-card {
  transition: all 0.3s ease;
}

.seckill-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.progress-text {
  font-size: 0.7rem;
  margin-top: 2px;
}

.batch-info {
  background: #f8f9fa;
  border-radius: 4px;
  padding: 4px 6px;
}
</style> 